package com.interview.javabasic.socket;

import java.net.DatagramPacket;
import java.net.DatagramSocket;
import java.net.InetAddress;
import java.util.Scanner;

public class UDPClient {
    public static void main(String[] args) throws Exception{
        //客户端发送数据给服务器端
        DatagramSocket socket = new DatagramSocket();
        //要发送给服务器端的数据
        Scanner scanner = new Scanner(System.in);
        String clientwords = scanner.next();
        byte[] buff = ("Client: " + clientwords).getBytes();
        InetAddress address = InetAddress.getByName("127.0.0.1");
        //将要发送给服务器端的数据封装成DataGramPacket对象，需要填写上ip地址与端口号
        DatagramPacket packet = new DatagramPacket(buff,buff.length,address,65001);
        //发送数据给服务器端
        socket.send(packet);

        //客户端接收服务器端发送过来的数据报
        byte[] data = new byte[100];
        //创建DatagramPacket对象用来存储服务器端发送的数据
        DatagramPacket receivePacket = new DatagramPacket(data,data.length);
        //将接收来的数据存储到DatagramPacket对象中
        socket.receive(receivePacket);
        //将服务器端发送过来的数据取出来并打印到控制台
        String content = new String(receivePacket.getData(),0,receivePacket.getLength());
        System.out.println(content);

    }
}

